#include"ip_can_fifo.h"
#include "xstatus.h"

static uint32_t axis_fifo_rd32(UINTPTR addr)
{
    uint32_t regVal = *(volatile uint32_t *) addr;
    return (regVal);
}

static void axis_fifo_wr32(UINTPTR addr, uint32_t value)
{
    *(volatile uint32_t *) addr = value;
}

/*��fifo��λȫ������A5*/
void axis_fifo_reset(UINTPTR BaseAddress)
{
	axis_fifo_wr32((BaseAddress + AXIS_FIFO_TDFR), 0xa5);
	axis_fifo_wr32((BaseAddress + AXIS_FIFO_RDFR), 0xa5);
	axis_fifo_wr32((BaseAddress + AXIS_FIFO_SRR), 0xa5);
}

unsigned int axis_fifo_read_data_len(UINTPTR BaseAddress)
{
	return axis_fifo_rd32(BaseAddress + AXIS_FIFO_RDFO) * 4;
}

int axis_fifo_read_data(UINTPTR BaseAddress, unsigned char *buffer, int length)
{
	if (length % 4)
		return -1;
	int i = 0;
	for(i = 0; i < length; i += 4)
		*(uint32_t*)(&buffer[i]) = axis_fifo_rd32(BaseAddress + AXIS_FIFO_RDFD);
    return i;
}

int axis_fifo_write_data(UINTPTR BaseAddress, unsigned char *buffer, int length)
{
	if (length % 4)
		return -1;
    int i = 0;
    uint32_t can_write = axis_fifo_rd32(BaseAddress + AXIS_FIFO_TDFV);
    // xil_printf("%d, %d\r\n", axis_fifo_rd32(BaseAddress + AXIS_FIFO_TDFV), length);
    while (can_write < length / 4)
    	can_write = axis_fifo_rd32(BaseAddress + AXIS_FIFO_TDFV);
	for(i = 0; i < length; i += 4)
		axis_fifo_wr32(BaseAddress + AXIS_FIFO_TDFD, *((uint32_t*)&buffer[i]));
	axis_fifo_wr32(BaseAddress + AXIS_FIFO_TLR, length);
    return i;
}

//int axis_fifo_read_data(UINTPTR BaseAddress, unsigned char *buffer, int length)
//{
//	int i = 0;
//	unsigned int data;
//	for(i = 0; i < length; i++) {
//		data = axis_fifo_rd32(BaseAddress + AXIS_FIFO_RDFD);
//		buffer[i]= (data & 0xff);
//
//	}
//    return i;
//}

//int axis_fifo_write_data(UINTPTR BaseAddress, unsigned char *buffer, int length)
//{
//	int i = 0;
//	unsigned int tmp = 0;
//	if(axis_fifo_rd32(BaseAddress + AXIS_FIFO_TDFV)) {
//		for(i = 0; i < length; i++) {
//			tmp = buffer[i];
//			axis_fifo_wr32(BaseAddress + AXIS_FIFO_TDFD, tmp);
//		}
//
//		axis_fifo_wr32(BaseAddress + AXIS_FIFO_TLR, length*4);
//	}
//
//	return i;
//}

